/**
 * @description ajax请求的封装
 */

const BASE_URL = "http://fitness.h5.itsource.cn:3701"; // 接口请求的 URL

/* ajax方法 */
function ajax(options) {
	// 默认参数
	const defaultOpts = {
		method: "get",
		data: {},
		headers: {},
	};

	// 合并参数
	const params = Object.assign({}, defaultOpts, options);

	// 获取参数值
	let method = params.method;
	let url = BASE_URL + params.url;
	let data = params.data;
	let success = params.success;
	let headers = params.headers;

	// 发送ajax
	const xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
		if (xhr.readyState === 4 && xhr.status === 200) {
			let response = JSON.parse(xhr.responseText);
			success(response);
		}
	};

	if (method === "get") {
		// 处理参数
		let str = "";
		Object.keys(data).forEach(function (key) {
			str += `&${key}=${data[key]}`;
		});
		str = str ? "?" + str.slice(1) : "";
		xhr.open(method, url + str);

		Object.keys(headers).length &&
			Object.keys(headers).forEach(function (key) {
				xhr.setRequestHeader(key, headers[key]);
			});

		xhr.send();
	} else {
		xhr.open(method, url);
		xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");

		Object.keys(headers).length &&
			Object.keys(headers).forEach(function (key) {
				xhr.setRequestHeader(key, headers[key]);
			});

		xhr.send(JSON.stringify(data));
	}
}

/* 简洁版的 get 封装 */
function get(url, callback) {
	ajax({
		url: url,
		method: "get",
		success: callback,
	});
}

/* 简洁版的 post 封装 */
function post(url, data, callback) {
	ajax({
		url: url,
		method: "post",
		data,
		success: callback,
	});
}

/* 导出 */
module.exports = {
	ajax,
	get,
	post,
};
